package CartService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/CartReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-member/CartService"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"time"
)

func getIsSelectedValue(IsSelected bool) int {
	if IsSelected == true {
		return 1
	} else {
		return 0
	}
}

func SaveSelected(ctx context.Context, parames *CartReq.SaveSelected) *response.JsonResponse {
	err := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		for _, item := range parames.Carts {
			_, err := tx.Model("member_cart").Unscoped().Update(g.Map{
				"is_selected": getIsSelectedValue(item.IsSelected),
				"update_at":   time.Now().Unix(),
			}, "id=? AND member_id=?", item.Id, parames.MemberId)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	} else {
		return response.SuccessByRequestMessageData(nil, "成功",
			CartService.BaseCount(ctx, parames.MemberId))
	}
}
